package com.sztest.jayjun.utils;

import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.sztest.jayjun.MyApplication;
import com.sztest.jayjun.R;


/*
 *  @项目名：  scanpen
 *  @包名：    com.chomp.scanpen.util
 *  @文件名:   ToastUtils
 *  @创建者:   okmin
 *  @创建时间:  2020/12/21 18:23
 *  @描述：    TODO
 */
public class ToastUtils {
    private static Toast sToast;


    public static void show(String msg){
        LogUtils.e(isMainThread()+"=show="+msg);
        if (isMainThread()) {
            showMain(msg);
        }else {
            MyApplication.getInstance().mHandler.post(new Runnable() {
                @Override
                public void run() {
                    showMain(msg);
                }
            });
        }
    }

    private static void showMain(String msg) {
        try {
            View layout = View.inflate(MyApplication.getInstance(), R.layout.toast_tips, null);
            TextView text_result = (TextView) layout.findViewById(R.id.text_result);
            text_result.setText(msg);
            if (sToast != null) {
                sToast.cancel();
                sToast=null;
            }
            if (sToast == null) {
                sToast = new Toast(MyApplication.getInstance().getApplicationContext());
            }

            sToast.setGravity(Gravity.CENTER, 0, 0);
            sToast.setDuration(Toast.LENGTH_SHORT);
            sToast.setView(layout);
            sToast.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void cancel(){
        if (sToast != null) {
            try {
                sToast.cancel();
                sToast=null;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }
}
